package pl.com.qapps.util.jar;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import pl.com.qapps.util.Extractor;

/**
 * The purpose of this class is to allow executing files which are in archives
 * or are not executable.
 * 
 * @author Jakub Dykowski
 * 
 */
// TODO delete
public class ScriptExtractor implements Extractor {

	private final static FileAttribute<?> ATTRIBUTES = PosixFilePermissions
			.asFileAttribute(PosixFilePermissions.fromString("rwx------"));
	private Path dir;

	/**
	 * The directory is root directory.
	 */
	public ScriptExtractor() {
	}

	/**
	 * 
	 * @param dir
	 *            the directory where put the files, if <code>null</code>, root
	 *            is used
	 * @throws IllegalArgumentException
	 */
	public ScriptExtractor(Path dir) throws IllegalArgumentException {
		if (dir != null && Files.notExists(dir) || Files.isDirectory(dir))
			throw new IllegalArgumentException(
					"directory doesn't exists or is nota directory");
	}

	@Override
	public Path extract(Path from, String filePath)
			throws NullPointerException, IOException {
		Objects.requireNonNull(from, "from cannot be null");
		Objects.requireNonNull(filePath, " filePath cannot be null");

		// Path file = Paths.get(from.toString(), filePath);
		// if (Files.exists(file) && Files.isExecutable(file))
		// return file;
		// else
		System.out.printf("prefix: %s suffix:%s", filePath, ".tmp");
		Path newFile;
		if (dir != null)
			newFile = Files.createTempFile(dir, filePath, ".tmp", ATTRIBUTES);
		else
			newFile = Files.createTempFile(filePath/*.replaceAll("/", ".")*/,
					".tmp", ATTRIBUTES);

		if (Files.isDirectory(from)) {
			Files.copy(Paths.get(from.toString(), filePath), newFile,
					StandardCopyOption.REPLACE_EXISTING);
		} else {
			ZipFile zip = new ZipFile(from.toFile());
			ZipEntry entry = zip.getEntry(filePath);
			Files.copy(zip.getInputStream(entry), newFile,
					StandardCopyOption.REPLACE_EXISTING);
		}
		System.out
				.println("script file extracted: " + newFile.toAbsolutePath());
		return newFile;
	}
}
